<template>
	<el-dialog v-model="isVisible" title="重置密码" width="500px" :before-close="handleClose">
		<el-form ref="formRef" class="good-service-form" :model="form" :rules="rules" label-width="120px" inline>
			<el-form-item label="登录密码" prop="password">
				<el-input v-model="form.password" show-password placeholder="输入登录密码" minlength="6" :maxlength="16" />
			</el-form-item>
			<el-form-item label="确认密码" prop="confirmPassword">
				<el-input v-model="form.confirmPassword" show-password placeholder="输入登录密码" minlength="6" :maxlength="16" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" v-debounce="submit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, watch } from 'vue';
import { fetchResetPwd } from '/@/api/system';
import { verifyPassword } from '/@/utils/toolsValidate';
import { Md5 } from 'ts-md5';

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

const isVisible = ref(false);

const formRef = ref();
const form = ref<any>({
	pass: true,
	reason: '',
});

const validatePassword = (rule: any, value: any, callback: any) => {
	if (!verifyPassword(value)) {
		callback(new Error('密码必须包含英文、数字、符号,长度在6-16之间'));
	} else {
		callback();
	}
};

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
	if (value !== form.value.password) {
		callback(new Error('两次输入的密码不一致'));
	} else {
		callback();
	}
};

//校验规则
const rules = reactive<FormRules<any>>({
	password: [
		{ required: true, message: '输入登录密码', trigger: 'blur' },
		{
			validator: validatePassword,
			trigger: 'blur',
		},
	],
	confirmPassword: [
		{ required: true, message: '输入登录密码', trigger: 'blur' },
		{
			validator: validateConfirmPassword,
			trigger: 'blur',
		},
	],
});

watch(
	() => props.visible,
	(val) => {
		isVisible.value = val;
	},
	{
		immediate: true,
	}
);

const submit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const password = Md5.hashStr(form.value.password);
			const res = await fetchResetPwd({ ...form.value, password, id: props.row.id });
			if (res.code == 200) {
				ElMessage.success('重置密码完成');
				handleClose();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const handleClose = () => {
	form.value = {};
	formRef.value.resetFields({});
	formRef.value.clearValidate();
	emit('handleClose');
};
</script>

<style lang="scss">
.good-service-form {
	.el-form-item {
		width: 90%;
		.el-input-number {
			width: 100%;
		}
	}
}
</style>
